package edu.njust.httpmanager.controller;

import edu.njust.httpmanager.annotation.AuthCheck;
import edu.njust.httpmanager.common.Result;
import edu.njust.httpmanager.common.UserContext;
import edu.njust.httpmanager.constance.ResponseCode;
import edu.njust.httpmanager.constance.UserAuth;
import edu.njust.httpmanager.entity.Program;
import edu.njust.httpmanager.entity.dto.ProgramDto;
import edu.njust.httpmanager.exception.CustomException;
import edu.njust.httpmanager.service.IProgramService;
import edu.njust.httpmanager.service.IUserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/program")
public class ProgramController {

    @Resource
    private IProgramService programService;

    @Resource
    private IUserService userService;

    @GetMapping("/{id}")
    public Result<ProgramDto> getUserProgramById(@PathVariable Long id) {

        Long userId = UserContext.getUser().getId();

        ProgramDto programDto = programService.getUserProgramWithAuthById(userId, id);

        return Result.success(programDto);
    }

    @AuthCheck(UserAuth.ADMIN)
    @PutMapping("/{id}")
    public Result<Void> update(@PathVariable Long id, @RequestBody Program program) {

        // 姓名不能修改为空
        if (program.getName() == null || StringUtils.isBlank(program.getName())) {
            throw new CustomException(ResponseCode.PARAMS_ERROR);
        }

        programService.updateById(program);

        return Result.success();
    }

    /**
     * 获取用户参与的所有项目
     */
    @GetMapping
    public Result<List<ProgramDto>> getUserPrograms(@RequestParam(value = "key", required = false) String key) {
        // 要返回的结果
        List<ProgramDto> programDtos;
        // 获取用户id
        Long userId = UserContext.getUser().getId();
        if (key == null) {
            programDtos = programService.getUserProgramWithAuth(userId);
        } else {
            String programName = '%' + key + '%';
            programDtos = programService.getUserProgramWithName(userId, programName);
        }

        return Result.success(programDtos);
    }

    /**
     * 保存项目
     */
    @PostMapping()
    public Result save(@RequestBody Program program) {

        Long userId = UserContext.getUser().getId();

        programService.saveWithAuth(program, userId);

        return Result.success();
    }

    /**
     * 删除项目
     *
     * @param id
     * @return
     */
    @AuthCheck(UserAuth.ADMIN)   // 通过枚举类指定可以避免写错
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Long id) {

        programService.deleteProgram(id);

        return Result.success();
    }


}
